import requests
import pymysql
import json
import _thread


#
# 获取吖咪直播所有的用户的用户数据 昵称性别
def get_index1(url):
    try:
        headers = {
            'Accept': 'application/json, text/plain, */*',
            'Accept - Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOjEyNiwiVXNlck5hbWUiOiJ6aGFuZ2hvbmciLCJOYW1lIjoi5byg5rSqIiwiUGFyZW50SWQiOjAsIlBhcmVudE5hbWUiOiIiLCJCdXNpbmVzc0ZlZSI6MCwiRmVlIjowLCJSb2xlcyI6WzE2XSwiUm9sZU5hbWUiOiLlvIDlj5HkurrlkZgiLCJJc0FkbWluIjpmYWxzZSwiRXhwaXJ5RGF0ZVRpbWUiOiIyMDIyLTAyLTIxVDEwOjQzOjI5LjIwMDIwNjcrMDg6MDAifQ.MYYlIPoM-xWEvHYxvFseK456sYXSXV6pysZA8tTy3B8',
            'Cookie': 'Admin-Token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOjEyNiwiVXNlck5hbWUiOiJ6aGFuZ2hvbmciLCJOYW1lIjoi5byg5rSqIiwiUGFyZW50SWQiOjAsIlBhcmVudE5hbWUiOiIiLCJCdXNpbmVzc0ZlZSI6MCwiRmVlIjowLCJSb2xlcyI6WzE2XSwiUm9sZU5hbWUiOiLlvIDlj5HkurrlkZgiLCJJc0FkbWluIjpmYWxzZSwiRXhwaXJ5RGF0ZVRpbWUiOiIyMDIyLTAyLTIxVDEwOjQzOjI5LjIwMDIwNjcrMDg6MDAifQ.MYYlIPoM-xWEvHYxvFseK456sYXSXV6pysZA8tTy3B8; sidebarStatus=0',
            'Host': 'htgl.yamizhibo.com',
            'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, '
                          'like Gecko) Chrome/90.0.4430.93 Mobile Safari/537.36',
            # 'accept-encoding': 'gzip, deflate, br',
        }
        response = requests.get(url, headers=headers, timeout=39)
        response.encoding = "utf-8"
        if response.status_code == 200:
            return response.text
    except Exception as e2:
        print('获取网页数据异常：' + str(e2))
        return None


def add_db(jsonss, str_msg):
    # 打开数据库连接，不指定数据库
    if isHome == 1:
        conn = pymysql.connect(host='localhost', user='root', password='XUHUAN.59')
    else:
        conn = pymysql.connect('localhost', 'root', 'xuhuan.5130638')
    conn.select_db('laimiao')
    cur = conn.cursor()  # 获取游标
    sunNum = 0
    try:
        # print("===========================================================================================================")
        # print(jsonss)
        jsonStr = json.loads(jsonss)
        for item in jsonStr['Data']['rows']:
            cur.execute("select * from user where uid=" + str(item["uid"]))
            # 使用 fetchone() 方法获取一条数据
            data = cur.fetchone()
            # print('添加语句受影响的行数：', data)
            if data is None:
                sql = "insert into user (uid,sex,cell,coin,gold_coin,mart,identification_name,identification_no," \
                      "spreaduid,islock,user_level,anchor_level,ip,cdt,plat,sver,register_time) " \
                      "values('{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}')".format(
                    item["uid"], item["sex"], item["cell"], item["coin"], item["gold_coin"], item["mart"],
                    item["identification_name"], item["identification_no"], item["spreaduid"],
                    item["islock"], item["user_level"], item["anchor_level"], item["ip"], item["cdt"], item["plat"],
                    item["sver"], item["register_time"]
                )
                # print(len(sql))
                sunNum += cur.execute(sql)
            else:
                sql = "update user set uid='{}',sex='{}',cell='{}',coin='{}',gold_coin='{}',mart='{}'," \
                      "identification_name='{}'" \
                      ",identification_no='{}',spreaduid='{}',islock='{}',user_level='{}',anchor_level='{}',ip='{}'" \
                      ",cdt='{}',plat='{}',sver='{}',register_time='{}' where uid='{}'".format(
                    item["uid"], item["sex"], item["cell"], item["coin"], item["gold_coin"], item["mart"],
                    item["identification_name"], item["identification_no"], item["spreaduid"],
                    item["islock"], item["user_level"], item["anchor_level"], item["ip"], item["cdt"], item["plat"],
                    item["sver"], item["register_time"], item["uid"]
                )
                sunNum += cur.execute(sql)
            conn.commit()
    finally:
        try:
            cur.close()
            conn.close()
            print(str_msg + '  受影响的行数：' + str(sunNum))
        except Exception as e1:
            print('sql执行成功异常：' + str(e1))


def get_data(name, start, end):
    for i in range(start, end):
        try:
            # http://htgl.cwoqu.com/api/basic/forbidlist?page=1&size=20
            # print("\n\n\n\n\n\n\n\n")
            # print("========================================= 开始获取数据 =================================================")
            str_msg = "                                     " + name + "Task_Page：" + str(i)
            add_db(get_index1("http://htgl.yamizhibo.com/api/users/userlist?page=" + str(i) + "&size=20"), str_msg)
            # print("========================================= 开始获取数据 =================================================")
        except Exception as e1:
            print('循环次数 ' + str(i) + ' 异常：' + str(e1))


isHome = 1   # 公司1 家2
if __name__ == '__main__':
    try:
        num = 0
        xs = 100
        _thread.start_new_thread(get_data, ("Thread-1----", num, num + xs))
        _thread.start_new_thread(get_data, ("Thread-2----", num + xs * 1, num + xs * 2))
        _thread.start_new_thread(get_data, ("Thread-3----", num + xs * 2, num + xs * 3))
        _thread.start_new_thread(get_data, ("Thread-4----", num + xs * 3, num + xs * 4))
        _thread.start_new_thread(get_data, ("Thread-5----", num + xs * 4, num + xs * 5))
    except IOError as e:
        print("Error: 无法启动线程")
    while 1:
        pass
